//
//  MKApplePayUtils.m
//  Fanmugua
//
//  Created by xiaomk on 2019/12/5.
//  Copyright © 2019 taolang. All rights reserved.
//

#import "MKApplePayUtils.h"
#import <StoreKit/StoreKit.h>
#import "HYProductModel.h"
#import "TLRechargeGoodsModel.h"
// 定义队列和全局订单映射

static NSString * const kHY_Order_Buy      = @"kHY_Order_Buy"; //收藏可选分组 开关
static dispatch_queue_t iapQueue;
@interface MKApplePayUtils()<SKPaymentTransactionObserver,SKProductsRequestDelegate,SKRequestDelegate>
@property (nonatomic, assign) BOOL isAuto;
@property (atomic, strong) NSMutableDictionary *orderMap;  // 线程安全的订单映射

@end

@implementation MKApplePayUtils
MK_IMPL_SHAREDINSTANCE(MKApplePayUtils)

- (id)init{
    if (self = [super init]) {
        self.isAuto = NO;
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
        iapQueue = dispatch_queue_create("com.huaya.iap.queue", DISPATCH_QUEUE_SERIAL);
    }
    return self;
}

- (void)saveLastOrder:(CGOrderModel * __nullable)info{
    if (info) {
        NSDictionary *dic = [info mj_keyValues];
        [MK_USERDEFAULTS setObject:dic forKey:@"CG_lastOrder"];
        [MK_USERDEFAULTS synchronize];
    }else{
        [MK_USERDEFAULTS removeObjectForKey:@"CG_lastOrder"];
    }
}

- (CGOrderModel * __nullable)getLastOrderInfo{
    NSDictionary *dic = [MK_USERDEFAULTS valueForKey:@"CG_lastOrder"];
    if (dic) {
        CGOrderModel *info = [CGOrderModel mj_objectWithKeyValues:dic];
        return info;
    }
    return nil;
}

#pragma mark - ***** SKPaymentTransactionObserver ******
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(nonnull NSArray<SKPaymentTransaction *> *)transactions{
//    [HYUtils hideLoadingView];
    
    [TL_UtilsHelper hideLoadingView];
    dispatch_async(iapQueue, ^{
        for (SKPaymentTransaction *tran in transactions) {
            NSLog(@"transactions : %@",[tran description]);
            NSLog(@"transactionIdentifier : %@",tran.transactionIdentifier);
            switch (tran.transactionState) {
                case SKPaymentTransactionStatePurchased:{
                    NSLog(@"交易完成");
                    if (tran.originalTransaction) {
                        NSLog(@"originalTransaction = %@",tran.originalTransaction);
                    }else{
                        NSLog(@"普通购买，以及第一次购买自动订阅");
                    }
                    NSString *orderUserId = [[tran payment] applicationUsername];
                    
                    if ((orderUserId && orderUserId.length > 0 && [TL_UserInfoManager.userInfo.userCardId  isEqualToString:orderUserId])
                        || (!orderUserId || orderUserId.length == 0)) {
                        [self completeTransaction:tran completeBlock:^{
                            [[MKApplePayUtils sharedInstance] saveLastOrder:nil];
                            [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                        }];
                    }
                }
                    break;
                case SKPaymentTransactionStatePurchasing:
//                    [HYUtils showLoadingViewWith:@"苹果验证中..." canCancel:NO];
                    NSLog(@"商品添加进列表");
                    break;
                case SKPaymentTransactionStateRestored:
                    NSLog(@"已经购买过商品");
                    [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                    break;
                case SKPaymentTransactionStateFailed:
                    NSLog(@"取消购买");
//                    [MKUtils showToast:@"您已取消购买"];
                    
                    if (self.restoreCancelBlock) {
                        self.restoreCancelBlock();
                    }
                    [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                    break;
                default:
                    break;
            }
        }
    });
    
}

- (void)completeTransaction:(SKPaymentTransaction *)transaction completeBlock:(MKVoidBlock)completeBlock{
    
    
    NSLog(@"transactionIdentifier : %@",transaction.transactionIdentifier);
    NSLog(@"transactionState : %@",@(transaction.transactionState));
    
    // 判断是否为恢复购买
    BOOL isRestore = (transaction.transactionState == SKPaymentTransactionStateRestored);
    
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];// appStoreReceiptURL iOS7.0增加的，购买交易完成后，会将凭据存放在该地址
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];// 从沙盒中获取到购买凭据
    NSString *encodeStr = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
//    NSLog(@"encodeStr : %@",encodeStr);
    // BASE64 常用的编码方案，通常用于数据传输，以及加密算法的基础算法，传输过程中能够保证数据传输的稳定性，BASE64是可以编码和解码的
    // 将票据POST给自己的服务器去校验...
    MJWeakSelf
    if (isRestore) {
        // 恢复购买逻辑：直接向服务器发送收据，无需订单号
        
        NSString *productId = transaction.payment.productIdentifier;
        
        NSString *orderNum = [self.orderMap objectForKey:productId];
        
        NSDictionary *param = @{
            @"transactionId": transaction.transactionIdentifier,
            @"receipt": encodeStr,
            @"orderNum" : orderNum,
        };
        
        [APIManager sendPostRequest:[APIURLManager applePayURL] parameters:param model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
            
            if (success) {
                MK_BLOCK_EXEC(completeBlock);
                MK_BLOCK_EXEC(weakSelf.completeTransactionBlock);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
            
        }];
        
    } else {
        CGOrderModel *orderInfo = [[MKApplePayUtils sharedInstance] getLastOrderInfo];
        
        NSString *productId = transaction.payment.productIdentifier;
        NSString *orderNum = [self.orderMap objectForKey:productId];
        
        
        if (orderNum && orderInfo && [orderInfo.orderNum isEqualToString:orderNum]) {
            if (self.isAuto) {
//                NSDictionary *param = @{
//                    @"transaction_id":transaction.transactionIdentifier,
//                    @"receipt" : encodeStr,
//                    @"orderNum" : orderNum,
//                    @"productName" : @"huaya",
//                    @"userId" : TL_UserInfoManager.userInfo.userCardId,
//                    @"payPlatform": @"IOS"
//                };
                
                
                
//                [CGRequestUtils sendRequestWith:CGReqDataType_Auto_products_applePay param:param block:^(CGResponseInfo * _Nullable response) {
//                    if (response.isSuccess) {
//                        MK_BLOCK_EXEC(completeBlock);
//                        MK_BLOCK_EXEC(weakSelf.completeTransactionBlock);
//                    }
//                }];
                
            }else{
                NSDictionary *param = @{
                    @"transactionId":transaction.transactionIdentifier,
                    @"receipt" : encodeStr,
                    @"orderNum" : orderNum,
                    @"price" : orderInfo.price,
                };
                NSLog(@"支付数据 ：%@",param);
                
                [APIManager sendPostRequest:[APIURLManager applePayURL] parameters:param model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
                    
                    if (success) {
                        MK_BLOCK_EXEC(completeBlock);
                        MK_BLOCK_EXEC(weakSelf.completeTransactionBlock);
                    }
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
                    
                }];
                
//                [CGRequestUtils sendRequestWith:CGReqDataType_payment_payment param:param block:^(CGResponseInfo * _Nullable response) {
//                    if (response.isSuccess) {
//                        MK_BLOCK_EXEC(completeBlock);
//                        MK_BLOCK_EXEC(weakSelf.completeTransactionBlock);
//                    }
//                }];
            }
        }
    }
}

- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue{
    [TL_UtilsHelper hideLoadingView];
    
//    [HYUtils hideLoadingView];
//    NSMutableArray *purchasedItemIDs = [[NSMutableArray alloc] init];
//    NSLog(@"received restored transactions: %@", @(queue.transactions.count));
//    for (SKPaymentTransaction *transaction in queue.transactions){
//        NSString *productID = transaction.payment.productIdentifier;
//        [purchasedItemIDs addObject:productID];
//    }
//    SKPaymentTransaction *lastTran = queue.transactions.lastObject;
//    if (lastTran) {
//        [self completeTransaction:lastTran completeBlock:nil];
//        NSLog(@"%@",purchasedItemIDs);
//    }else{
//        [MKUtils showToast:@"暂无可恢复的已购买记录"];
//    }
    if (queue.transactions.count == 0) {
//        [MKUtils showToast:@"没有可恢复的订单哦~"];
        
        if (self.restoreCancelBlock) {
            self.restoreCancelBlock();
        }
        return;
    }
    for (SKPaymentTransaction *transaction in queue.transactions) {
        [self completeRestoredTransaction:transaction];
    }
}
- (void)completeRestoredTransaction:(SKPaymentTransaction *)transaction {
    
    if (transaction.transactionState == SKPaymentTransactionStateRestored) {
        [self completeTransaction:transaction completeBlock:^{
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        }];
    }
}
- (void)restorePurchases {
    
    [TL_UtilsHelper showLoadingViewWith:@"recovering..." canCancel:NO];
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}
- (void)paymentQueue:(SKPaymentQueue *)queue restoreCompletedTransactionsFailedWithError:(NSError *)error{
    
    [TL_UtilsHelper hideLoadingView];
//    [MKUtils showToast:@"There are no recoverable orders~"];
    if (self.restoreCancelBlock) {
        self.restoreCancelBlock();
    }
    NSLog(@"%@",[error description]);
}

- (BOOL)paymentQueue:(SKPaymentQueue *)queue shouldAddStorePayment:(SKPayment *)payment forProduct:(SKProduct *)product API_AVAILABLE(ios(11.0)){
    NSLog(@"paymentQueue:shouldAddStorePayment");
    return YES;
}

#pragma mark - ***** createOrder ******
- (void)createOrderWithItem:(TLRechargeGoodsModel *)itemInfo novelId:(NSNumber *__nullable)novelId videoId:(NSNumber *__nullable)videoId andIsAuto:(BOOL)isAuto{
    
    self.isAuto = isAuto;
    
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kHY_Order_Buy];
    
    NSNumber *product_id = itemInfo.goodsId;
    if (!product_id) {
        product_id = itemInfo.goodsId;
    }
    
    NSMutableDictionary *param = @{
        @"productId" : itemInfo.goodsId
    }.mutableCopy;
    
    if (novelId) {
        [param setValue:novelId forKey:@"novel_id"];
    }
    if (videoId){
        [param setValue:videoId forKey:@"video_id"];
    }
    [param setValue:@"0" forKey:@"payPlatform"];
    
    if (isAuto) {
        
        if (TL_UserInfoManager.isLogin) {
            [param setValue:TL_UserInfoManager.userInfo.userCardId forKey:@"userId"];
        }
        
        [param setValue:product_id forKey:@"productId"];
        
        MJWeakSelf
//        [CGRequestUtils sendRequestWith:CGReqDataType_Auto_products_applePrepay param:param.copy block:^(CGResponseInfo * _Nullable response) {
//            if (response.isSuccess) {
//                
//                NSString *orderNum = response.data[@"orderNum"];
//
//                if (orderNum) {
//                    
//                    dispatch_barrier_async(iapQueue, ^{
//                        if (!self.orderMap) {
//                            self.orderMap = [[NSMutableDictionary alloc] init];
//                        }
//                        [self.orderMap setObject:orderNum forKey:itemInfo.itemid];
//                    });
//                    
//                    CGOrderModel *info = [[CGOrderModel alloc] init];
//                    info.orderNum = orderNum;
//                    info.price = itemInfo.price;
//                    
//                    if (!itemInfo.itemid) {
//                        info.itemid = itemInfo.appleSubProductId;
//                    }else{
//                        info.itemid = itemInfo.itemid;
//                    }
//                    
//                    info.productid = itemInfo.productid;
//                    [[MKApplePayUtils sharedInstance] saveLastOrder:info];
//                    [weakSelf startRequestAppStroreProduceWith:itemInfo.appleSubProductId];
//                }
//            }
//        }];
    }else{
        MJWeakSelf
        
        [APIManager sendPostRequest:[APIURLManager applePrepayURL] parameters:param model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
            
            if (success) {
                //                NSString *orderNum = response.orderNum;
                NSString *orderNum = requestModel.data[@"orderNum"];
                if (orderNum) {
                    
                    dispatch_barrier_async(iapQueue, ^{
                        if (!self.orderMap) {
                            self.orderMap = [[NSMutableDictionary alloc] init];
                        }
                        
                        [self.orderMap setObject:orderNum forKey:itemInfo.appleProductId];
                        
                    });
                    
                    CGOrderModel *info = [[CGOrderModel alloc] init];
                    info.orderNum = orderNum;
                    info.price = itemInfo.price;
                    info.itemid = itemInfo.appleProductId;
                    info.productid = itemInfo.goodsId;
                    [[MKApplePayUtils sharedInstance] saveLastOrder:info];
                    [weakSelf startRequestAppStroreProduceWith:itemInfo.appleProductId];
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
            
        }];
        
    }
}

- (void)startRequestAppStroreProduceWith:(NSString *)itemid{
    NSLog(@"%@",itemid);
    
    if ([SKPaymentQueue canMakePayments]) {
        NSArray *products = [[NSArray alloc] initWithObjects:itemid, nil];
        NSSet *set = [NSSet setWithArray:products];
        
        SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
        request.delegate = self;
        [request start];
        [TL_UtilsHelper showLoadingViewWith:@"获取数据中..." canCancel:NO];
    }else{
        
        [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"该设备不允许支付")];
    }
}

#pragma mark - ***** SKProductsRequestDelegate ******
//接收到产品的返回信息，然后用返回的商品信息进行发起购买请求
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    
    [TL_UtilsHelper hideLoadingView];
    NSArray *products = response.products;
    if (products.count == 0) {
        [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"苹果商店未找到该商品")];
        return;
    }
    
    SKProduct *requestProduct = nil;
    CGOrderModel *buyInfo = [[MKApplePayUtils sharedInstance] getLastOrderInfo];
    if (buyInfo == nil) {
        return;
    }
    for (SKProduct *pro in products) {
        NSLog(@"%@", [pro description]);
        NSLog(@"%@", [pro localizedTitle]);
        NSLog(@"%@", [pro localizedDescription]);
        NSLog(@"%@", [pro price]);
        NSLog(@"%@", [pro productIdentifier]);
        
        if ([pro.productIdentifier isEqualToString:buyInfo.itemid]) {
            requestProduct = pro;
            break;
        }
    }
    if (requestProduct) {
        SKMutablePayment *payment = [SKMutablePayment paymentWithProduct:requestProduct];
        payment.applicationUsername = TL_UserInfoManager.userInfo.userCardId;
        [[SKPaymentQueue defaultQueue] addPayment:payment];
        [TL_UtilsHelper showLoadingViewWith:@"苹果验证中..." canCancel:NO];
    }else{
        
        [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"选择商品不存在")];
    }
}

#pragma mark - ***** SKRequestDelegate ******
- (void)requestDidFinish:(SKRequest *)request{
    NSLog(@"信息反馈结束");
}

- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    NSLog(@"error : %@", error);
    
    [TL_UtilsHelper hideLoadingView];
    
    [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"收藏成功")];
}
@end
